package org.tpc.yn.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class JSONUtil {
    public static boolean IsJSON(String content) {
        try {
            if(content.equals("\"\"")){
                return false;
            }
            JSONObject.parseObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean IsJSONArray(String content) {
        try {
            JSONArray.parseArray(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static JSONObject transToLowerObject(String json) {
        JSONObject JSONObject2 = new JSONObject();
        JSONObject JSONObject1 = JSON.parseObject(json);
        for (String key : JSONObject1.keySet()){
            Object object = JSONObject1.get(key);
            if (object.getClass().toString().endsWith("JSONObject")) {
                JSONObject2.put(key.toLowerCase(), transToLowerObject(object.toString()));
            } else if (object.getClass().toString().endsWith("JSONArray")) {
                JSONObject2.put(key.toLowerCase(), transToArray(JSONObject1.getJSONArray(key).toString()));
            }else{
                JSONObject2.put(key.toLowerCase(), object);
            }
        }
        return JSONObject2;
    }

    public static JSONArray transToArray(String jsonArray) {
        JSONArray jSONArray2 = new JSONArray();
        JSONArray jSONArray1 = JSON.parseArray(jsonArray);
        for (int i = 0; i < jSONArray1.size(); i++) {
            Object jArray = jSONArray1.getJSONObject(i);
            if (jArray.getClass().toString().endsWith("JSONObject")) {
                jSONArray2.add(transToLowerObject( jArray.toString()));
            } else if (jArray.getClass().toString().endsWith("JSONArray")) {
                jSONArray2.add(transToArray(jArray.toString()));
            }
        }
        return jSONArray2;
    }

    public static String jsonValueArrToString(String jsonData) {
        String newJsonData = "";
        try {
            // 将 JSON 字符串解析为 JSONObject
            JSONObject jsonObject = JSONObject.parseObject(jsonData);
            JSONObject newJsonObject = new JSONObject();

            // 遍历原始 JSON
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);

                // 如果值是 JSONArray 类型，获取第一个元素
                if (value instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) value;
                    if (jsonArray.size() > 0) {
                        newJsonObject.put(key, jsonArray.get(0));
                    }
                } else {
                    // 其他类型的值直接添加到新的 JSONObject
                    newJsonObject.put(key, value);
                }
            }

            // 转换后的 JSON 字符串
            newJsonData = newJsonObject.toJSONString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return newJsonData;
    }

    public static String mapToJson(Map<String, Object> map) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
            return null;
        }
    }


    public static JSONObject convertKeysToUpper(JSONObject jsonObject) {
        JSONObject newJsonObject = new JSONObject();

        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            String newKey = key.toUpperCase();  // 将键转换为大写

            if (value instanceof JSONObject) {
                // 如果值为嵌套的 JSON 对象，则递归调用 convertKeysToUpper 方法
                newJsonObject.put(newKey, convertKeysToUpper((JSONObject) value));
            } else {
                // 其他类型的值直接放入新的 JSON 对象中
                newJsonObject.put(newKey, value);
            }
        }

        return newJsonObject;
    }

    public static String convertToJsonToKeyValueData(JSONObject jsonObject) {
        Map<String, Object> keyValueData = new HashMap<>();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            keyValueData.put(entry.getKey(), entry.getValue());
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : keyValueData.entrySet()) {
            stringBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode((String) entry.getValue())).append("&");
        }
        stringBuilder.deleteCharAt(stringBuilder.length() - 1); // 删除最后一个多余的"&"
        return stringBuilder.toString();
    }


    public static String strToJson(String str) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(str);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static List<List<String>> jsonArrayToListOfLists(JSONArray jsonArray) {
        List<List<String>> listOfLists = new ArrayList<>();

        for (int i = 0; i < jsonArray.size(); i++) {
            List<String> innerList = new ArrayList<>();
            JSONObject obj = jsonArray.getJSONObject(i);
            for (String key : obj.keySet()) {
                String value = obj.getString(key);
                innerList.add(value);
            }
            listOfLists.add(innerList);
        }
        return listOfLists;
    }

    public static JSONArray convertResultSetsToList(List<Object[]> results) {
        JSONArray jsonArray = new JSONArray();
        for (Object[] row : results) {
            JSONArray rowArray = new JSONArray();
            for (Object value : row) {
                rowArray.add(value);
            }
            jsonArray.add(rowArray);
        }
        return jsonArray;
    }



}
